<template>
  <div>
    <h2>实时监测</h2>
    
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-select v-model="selectedSensorType" placeholder="选择传感器类型" clearable>
          <el-option label="pH传感器" value="ph" />
          <el-option label="湿度传感器" value="moisture" />
          <el-option label="温度传感器" value="temperature" />
          <el-option label="SOC传感器" value="soc" />
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>实时数据流</span>
          </template>
          <el-table :data="realtimeData" style="width: 100%">
            <el-table-column prop="sensor_id" label="传感器ID" width="120" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getTypeTag(row.type)">{{ row.type }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="数值" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column label="位置">
              <template #default="{ row }">
                {{ row.location.lat.toFixed(4) }}, {{ row.location.lng.toFixed(4) }}
              </template>
            </el-table-column>
            <el-table-column prop="timestamp" label="时间" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-4">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>实时pH值变化</span>
          </template>
          <v-chart :option="phChartOption" style="height: 300px" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>实时湿度变化</span>
          </template>
          <v-chart :option="moistureChartOption" style="height: 300px" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getRealtimeData } from '../api/dashboard'

const selectedSensorType = ref('')
const realtimeData = ref([])
const phChartOption = ref({
  xAxis: { type: 'time' },
  yAxis: { type: 'value', name: 'pH值' },
  series: [{
    type: 'line',
    smooth: true,
    data: []
  }]
})

const moistureChartOption = ref({
  xAxis: { type: 'time' },
  yAxis: { type: 'value', name: '湿度(%)' },
  series: [{
    type: 'line',
    smooth: true,
    data: []
  }]
})

let refreshInterval = null

const getTypeTag = (type) => {
  const tags = {
    ph: 'primary',
    moisture: 'success',
    temperature: 'warning',
    soc: 'info'
  }
  return tags[type] || 'default'
}

const refreshData = async () => {
  try {
    const response = await getRealtimeData(selectedSensorType.value)
    realtimeData.value = response.sensors
    
    // 更新图表数据
    const now = new Date()
    if (response.sensors.length > 0) {
      const phData = response.sensors
        .filter(s => s.type === 'ph')
        .map(s => [now, s.value])
      
      const moistureData = response.sensors
        .filter(s => s.type === 'moisture')
        .map(s => [now, s.value])
      
      if (phData.length > 0) {
        phChartOption.value.series[0].data = [...phChartOption.value.series[0].data, ...phData].slice(-20)
      }
      
      if (moistureData.length > 0) {
        moistureChartOption.value.series[0].data = [...moistureChartOption.value.series[0].data, ...moistureData].slice(-20)
      }
    }
  } catch (error) {
    console.error('获取实时数据失败:', error)
  }
}

onMounted(() => {
  refreshData()
  refreshInterval = setInterval(refreshData, 5000) // 每5秒刷新一次
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>
